using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;

namespace BS.Read.Api;

public class QiniuUtils
{
    private readonly IConfiguration _configuration;

    public QiniuUtils(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    /// <summary>
    /// 上传文件到七牛云
    /// </summary>
    /// <param name="data">要上传的文件数据</param>
    /// <param name="saveKey">文件在七牛云中的保存名称</param>
    public string UploadFile(byte[] data, string saveKey)
    {
        // 校验输入参数
        if (data == null || data.Length == 0)
        {
            throw new ArgumentException("上传的数据不能为空", nameof(data));
        }

        if (string.IsNullOrWhiteSpace(saveKey))
        {
            throw new ArgumentException("保存的文件名不能为空", nameof(saveKey));
        }

        // 从配置中获取 AccessKey 和 SecretKey
        var accessKey = _configuration["QiNiu:AccessKey"];
        var secretKey = _configuration["QiNiu:SecretKey"];
        if (string.IsNullOrWhiteSpace(accessKey) || string.IsNullOrWhiteSpace(secretKey))
        {
            throw new InvalidOperationException("七牛云的 AccessKey 或 SecretKey 未配置");
        }

        string bucket = "picture15901026041";

        // 创建上传策略
        PutPolicy putPolicy = new PutPolicy
        {
            Scope = bucket,
        };
        // 设置上传凭证有效期（示例2小时，可调整）
        putPolicy.SetExpires(3600);

        // 自动选择区域
        Qiniu.Common.Config.AutoZone(accessKey, bucket, false);

        // 生成上传凭证
        string jstr = putPolicy.ToJsonString();
        string token = Auth.CreateUploadToken(new Mac(accessKey, secretKey), jstr);
        UploadManager um = new UploadManager();

        // 上传数据
        HttpResult result = um.UploadData(data, saveKey, token);
        if (result.Code == 200)
        {
            Console.WriteLine(result.Text);
            return "http://soozboaq0.hn-bkt.clouddn.com/" + saveKey;


        }
        else
        {
            Console.WriteLine("上传失败: " + result.Text);
            throw new Exception($"上传失败，状态码: {result.Code}, 错误信息: {result.Text}");
        }
    }
}
//http://soozboaq0.hn-bkt.clouddn.com/20241224195552%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202023-10-16%20152722.png?e=1735041764&token=o6ZDP22Bd8aA629rBp2cjfEaP3R3yIhzw_VbvvLI:pbH1wQWF0OJAYu_UA-6RTNVicuw=


//http://soozboaq0.hn-bkt.clouddn.com/20241224195552%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202023-10-16%20152722.png